var express = require('express');
var router = express.Router();
var mgdb = require('../../../utils/mgdb');
/* GET home page. */
router.patch('/', function (req, res, next) {
    // cart更改
    let { username, goodid, num } = req.query
    if (!username || !goodid) {
        res.send({ err: 1, msg: '用户名,商品信息为必传参数' })
        return
    }
    num = parseInt(num)
    req.mgdb.open({ collectionName: 'cart' }).then(({ collection, client }) => {
        collection.find({ username: username }).toArray((err, result) => {
            if (err) {
                res.send({ err: 1, msg: '操作集合失败' });
            } else {
                let index;
                // 遍历用户购物车里的商品，判断商品索引
                let flag = result[0].goods.some((val, idx) => {
                    index = idx;
                    return val.proid === goodid
                })
                if (flag) {
                    // 存在,判断加上或者减少后,该商品的数量情况
                    if (result[0].goods[index].num + num <= 0) {
                        //清除本条商品信息
                        result[0].goods.splice(index, 1)
                        goods = result[0].goods
                    } else {
                        // 加上减少的数量后大于零,修改该条商品的数量
                        result[0].goods[index].num = result[0].goods[index].num + num;
                        result[0].goods[index].time = Date.now()
                        goods = result[0].goods
                    }
                    collection.updateOne({ username: username }, { $set: { goods } }, { upsert: false, projection: false }, (err, result) => {
                        if (err) {
                            res.send({ err: 1, msg: '操作集合失败' });
                        } else {
                            res.send({ err: 0, msg: '修改数量成功', data: result.result })
                        }
                        client.close();
                    })
                } else {
                    res.send({ err: 1, msg: "未找到该条商品信息，请确认商品id" })
                }
            }
        })
    }).catch(
        e => res.send(e)
    )


})
module.exports = router;